import api from './api.js';
import vues from '../main.js'
import {
	getParamsBydecodeURI
} from '../util/util'

class SingleLogin {
	constructor() {
		this.instance = null
		this.openId = null
		this._resolve = null
		this._check = false
		this.token = null
		this.callbacks = []
		this.approval_remark = null
		this.NeedOpenid = null
	}

	static getInstance() {
		if (!this.instance) {
			this.instance = new SingleLogin()
		}
		return this.instance
	}
	async _check_session() {
		return new Promise((resolve, reject) => {
			uni.checkSession({
				success: function (res) {
					resolve(true)
				},
				fail: function (res) {
					reject()
				}
			})
		}).catch(err => { })
	}
	async _wxLogin() {
		return new Promise((resolve, reject) => {
			uni.login({
				success: res => {
					resolve(res.code)
				},
				fail: err => {
					reject()
				},
				complete: (msg) => {
					console.log(msg, 'msg')
				}
			})
		}).catch(err => { })
	}
	async code_totoken() {
		let newCode = await this._wxLogin();
		return new Promise(async (resolve, reject) => {
			let res = await this._request(api.GetProgramToken, {
				Js_code: newCode,
				ProgramCate: "Wechat"
			});

			if (res.Success) {
				this.NeedOpenid = res.Data.IsNeedSecondOpenid;
				vues.$store.dispatch('setOpenid', res.Data.Openid);
				vues.$store.dispatch('setToken', res.Data.Token);
				// 存token
				uni.setStorageSync('Openid', res.Data.Openid);
				uni.setStorageSync('Token', res.Data.Token);
				this.token = res.Data.Token;
				resolve(res.Data.Token)
			} else {
				reject()
			}
		}).catch(err => { })
	}
	getToken() {
		return new Promise(async (resolve, reject) => {
			this.callbacks.push(resolve)

			if (SingleLogin.getInstance().token) {
				resolve(SingleLogin.getInstance().token)
			} else {
				// start模板阶段统一拿测试token
				// let token = await this._getTestToken()
				// this.token = token
				// resolve(SingleLogin.getInstance().token)
				// return
				// end模板阶段统一拿测试token
				if (process.env.NODE_ENV == 'development') {

					let token = await this._getTestToken()
					this.token = token
					resolve(SingleLogin.getInstance().token)
				} else {
					let localToken = uni.getStorageSync('Token');
					if (localToken) {
						resolve(SingleLogin.getInstance().token)


					} else {
						let AuthorizationCode = getParamsBydecodeURI('AuthorizationCode');

						if (AuthorizationCode) {
							let token = await this._exchangeToken(AuthorizationCode)
							uni.setStorageSync('Token',token);
							this.token = token
							resolve(SingleLogin.getInstance().token)
						} else {
							this._yhLogin()
							reject()
						}
					}
					resolve(SingleLogin.getInstance().token)
				}
			}



		}).catch(err => { })
	}
	async _getTestToken() {
		// let param ={"OpenId": ""}
		let param = { "OpenId": "" }

		let url = api.GetTestToken;
		let res = await this._request(url, param)
		if (res.Success) {
			this.openId = res.Data.OpenId;
			uni.setStorageSync('Token',res.Data.Token);
			uni.setStorageSync('Openid',res.Data.OpenId);
			return res.Data.Token
		}
	}
	async _exchangeToken(code) {
		let param = {
			AuthorizationCode: code
		}
		let url = api.GetToken;
		let res = await this._request(url, param)
		if (res.Success) {
			this.openId = res.Data.FirstOpenId;
			uni.setStorageSync('Openid',res.Data.OpenId);
			return res.Data.Token
		}

		if (res.ReturnCode == 300006) { //授权码失效
			this.clearToken();
			this._yhLogin();
		}

	}
	checkLogin(token) {

		return new Promise(async (resolve, reject) => {

			let res = await this._request(api.GetWebConfig);

			if (res.Success) {
				this.token = token;
				this.NeedOpenid = res.Data.IsNeedOpenId;
				resolve(token)
			} else {
				reject()
			}
		}).catch(err => { })
	}
	_yhLogin() {

		let url = `${api.getAuthorizationCode}?pageUrl=${encodeURIComponent(window.location.href)}`

		window.location.replace(url)
	}
	async _request(url, data) {
		return new Promise((resolve, reject) => {

			uni.request({
				url: url,
				data: data,
				method: 'POST',
				header: {
					'content-type': 'application/x-www-form-urlencoded',
					'Authorization': uni.getStorageSync('Token') || ''
				},
				success: (res => {

					resolve(res.data);
				}),
				fail: (res => {
					console.log(res)
					reject()
				})
			})
		}).catch(err => { })
	}


	clearToken() {
		SingleLogin.getInstance().token = null
		uni.removeStorageSync('Token')
	}
}
export default SingleLogin
